package ic.doc.co2nudge.client;

import ic.doc.co2nudge.client.utils.DataServiceFactory;
import ic.doc.co2nudge.client.utils.UserService;
import ic.doc.co2nudge.client.utils.events.DataEvent;
import ic.doc.co2nudge.client.utils.events.DataLoadedEventHandler;
import ic.doc.co2nudge.client.utils.events.DataLoadedListener;
import ic.doc.co2nudge.client.utils.events.UserServiceEvent;
import ic.doc.co2nudge.client.utils.events.UserServiceEventHandler;
import ic.doc.co2nudge.client.widgets.MainPage;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.visualizations.corechart.LineChart;

/**
 * 
 * @author jm
 * 
 * */

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Co2nudge implements EntryPoint {
	
	@UiField MainPage mainPage;
	
	private DockLayoutPanel dockPanel=
		new DockLayoutPanel(Unit.EM);
	
	@Override
	public void onModuleLoad() {		
		authenticate();
	}
	
	
	//authentication
	private void authenticate() {
		
		UserService.addUserServiceEventListener( new UserServiceEventHandler(){
			
			@Override
			public void done(UserServiceEvent e) {
				if (e.isCompletedSuccessfully())
					initialize(false);
			}
		});
		
		UserService.getUserService()
			.authenticate("james", "123");
	}	
	
	//initializing application
	private void initialize(boolean genDictionary){
		
		if (genDictionary) {
			DataServiceFactory.addDataLoadedListener( 
					new DataLoadedListener(){

						@Override
						public void dataLoaded(DataEvent e) {
							
							DataServiceFactory.removeDataLoadedListener();
							loadDictionary();
						}
					});
			
			DataServiceFactory.generate();			
		}
		else
			loadDictionary();
	}
	
	//loading dictionary data
	private void loadDictionary(){
		
		DataServiceFactory.addDataLoadedListener(
				new DataLoadedEventHandler() {
					
					@Override
					public void dataLoaded(DataEvent e) {
						if (e.isCompletedSuccessfully()){
							buildUI();
						}
						else
							Window.alert("Error!");
						
						DataServiceFactory.removeDataLoadedListener();
					}
				});
		
		DataServiceFactory.loadDictionaryData();
	} 
	
	//building UI elements
	protected void buildUI(){
		
	    VisualizationUtils
	    	.loadVisualizationApi( new Runnable(){
				@Override
				public void run() { }	    		
	    	}, LineChart.PACKAGE );
		
		MainPage mainPage=new MainPage();
		mainPage.addStyleName("mainPage");	
		
		dockPanel.addWest(mainPage, 60);
		RootLayoutPanel.get()
			.add(dockPanel); 
	}	
}
